package org.yi.web.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.common.Constants;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.enums.BlockTypeEnum;
import org.yi.core.model.Pagination;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.block.entity.BlockEntity;
import org.yi.web.post.entity.PostEntity;
import org.yi.web.sys.entity.SiteEntity;

import com.jfinal.core.Controller;

/**
 * Controller基类， 放一些Controller中的公共方法
 * @author qq
 *
 */
public class BaseController extends Controller {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	/** http get请求 **/
	protected static final String METHOD_GTE = "get";
	/** http post请求 **/
	protected static final String METHOD_POST = "post";
	
	/** 请求处理成功 */
	protected static final String SUCCESS = "1";
	
	/** 请求处理失败 */
	protected static final String ERROR = "0";
	
	protected Map<String, Object> blocks = new HashMap<String, Object>();
	
	public SiteEntity getSite() {
		return SiteEntity.dao.getSite();
	}
	
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 */
	protected void addMessage(String msg){
		setAttr("msg", msg);
	}
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 * @param params	参数
	 */
	protected void addMessage(String msg, Object... params) {
		msg = String.format(msg, params);
		addMessage(msg);
	}
	/**
	 * 在request对象中添加返回前台的错误信息
	 * @param msg
	 */
	protected void addError(String msg){
		setAttr("error", msg);
	}
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 * @param params	参数
	 */
	protected void addError(String msg, Object... params) {
		msg = String.format(msg, params);
		addError(msg);
	}
	
	/**
	 * 跳转到全局错误页面
	 */
	public void error() {
		render("error.html");
	}
	
	/**
	 * 获取客户端请求方式，如get和post等
	 * @return
	 */
	protected final String getHttpMethod(){
		return getRequest().getMethod();
	}
	
	/**
	 * 是否是get方法访问
	 * @return
	 */
	protected boolean isGetMethod(){
		return METHOD_GTE.equalsIgnoreCase(getHttpMethod());
	}
	
	/**
	 * 是否是post方法访问
	 * @return
	 */
	protected boolean isPostMethod(){
		return METHOD_POST.equalsIgnoreCase(getHttpMethod());
	}
	
	protected Pagination getPager() {
		int pageNumber = StringUtils.isBlank(getPara("pageNumber")) ? 1 : getParaToInt("pageNumber");
		int pageSize = StringUtils.isBlank(getPara("pageSize")) ? Constants.DEFAULT_PAGESIZE : getParaToInt("pageSize");
		return new Pagination(pageNumber, pageSize);
	}
	
	protected AccountEntity getCurrentUser() {
		return (AccountEntity) SecurityUtils.getSubject().getSession(true).getAttribute(Constants.KEY_LOGIN_ACCOUNT);
	}
	
	public AccountEntity getFrontUser() {
		return getRequest() == null ? null : (AccountEntity) getSession(true).getAttribute(Constants.FRONT_LOGIN_USER);
	}
	
	protected void loadBlocks(){
		loadBlocks(BlockTargetEnum.ALL);
	}
	
	protected void loadBlocks(BlockTargetEnum target) {
		if(target == null) target = BlockTargetEnum.ALL;
		List<BlockEntity> blockList = BlockEntity.dao.getByTarget(target);
		for(BlockEntity b : blockList) {
			if(BlockTypeEnum.STANDARD.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
				// 标准文章列表
				List<PostEntity> articleList = new ArrayList<PostEntity>();
				try {
					articleList = PostEntity.dao.getByBlock(b);
				} catch (Exception e) {
					logger.debug("get standard article list error: " + e.getMessage());
					e.printStackTrace();
				}
				blocks.put(b.getStr("name"), articleList);
			} else if(BlockTypeEnum.CUSTOMIZE.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
				//指定文章
				List<PostEntity> articleList = new ArrayList<PostEntity>();
				try {
					articleList = PostEntity.dao.getByIds(b);
				} catch (Exception e) {
					logger.debug("get customize article list error: " + e.getMessage());
					e.printStackTrace();
				}
				/*//将查询出的文章按照区块指定的顺序放入新的列表中
				List<PostEntity> newArticleList = new ArrayList<PostEntity>();
                String[] ids = StringUtils.split(String.valueOf(b.get("content")), ",");
                for (String no : ids) {
                    for (PostEntity article : articleList) {
                        if (StringUtils.equals(no, String.valueOf(article.get("id")))) {
                            newArticleList.add(article);
                            // 查询出的文章放入缓存中
                            
                            // 减少循环次数，将已经取出的元素删掉
                            articleList.remove(article);
                            break;
                        }
                    }
                }*/
				blocks.put(b.getStr("name"), articleList);
			}  else if (BlockTypeEnum.HTML.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
                // HTML区块
				blocks.put(b.getStr("name"), b.get("content"));
            }  else if (BlockTypeEnum.RANDOM.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
                // 随机文章列表(全站)
            	List<PostEntity> articleList = new ArrayList<PostEntity>();
				try {
					articleList = PostEntity.dao.getRandom(b);
				} catch (Exception e) {
					logger.debug("get random article list error: " + e.getMessage());
					e.printStackTrace();
				}
				blocks.put(b.getStr("name"), articleList);
            } else if (BlockTypeEnum.CATEGORY.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
                // 随机文章列表(同类)
            	List<PostEntity> articleList = new ArrayList<PostEntity>();
				try {
					String cid = getPara("cid");
					articleList = PostEntity.dao.getRandom(b, cid);
				} catch (Exception e) {
					logger.debug("get random article list error: " + e.getMessage());
					e.printStackTrace();
				}
				blocks.put(b.getStr("name"), articleList);
            }
		}
		setAttr("blocks", blocks);
	}
}
